// miniprogram/pages/card/add/add.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isRunning: true,
    isCrossCountry: false,
    isGym: false,
    isRope: false,
    isLevel: false,
    show: false,
    selectIndex: 0,
    distance: "",
    time: "",
    speed: "",
    message: "",
    level: "",
    ropeNo: "",
    heartrate: "",
    calorie: "",
    types: "",
    altitude: "",
    images: [],
    cloudPath: [],
    isUploadingImg: false,
    isAddCarding: false,
    isRace: false,
    isActivity: false,
  },

  onClose() {
    this.setData({ show: false });
  },

  onClickType() {
    this.setData({ show: true });
  },

  onSelect(event) {
    console.log(event);
    switch (event.detail.name) {
      case "跑步卡":
        this.setData({
          selectIndex: 0,
          isRunning: true,
          isCrossCountry: false,
          isGym: false,
          isRope: false,
          isLevel: false,
          isActivity: false,
        });
        break;
      case "力量卡":
        this.setData({
          selectIndex: 1,
          isRunning: false,
          isCrossCountry: false,
          isGym: true,
          isRope: false,
          isLevel: false,
          isActivity: false,
        });
        break;
      case "越野卡":
        this.setData({
          selectIndex: 2,
          isRunning: true,
          isCrossCountry: true,
          isGym: false,
          isRope: false,
          isLevel: false,
          isActivity: false,
        });
        break;
      case "跳绳":
        this.setData({
          selectIndex: 3,
          isRunning: false,
          isCrossCountry: false,
          isGym: false,
          isRope: true,
          isLevel: false,
          isActivity: false,
        });
        break;
      case "爬楼梯":
        this.setData({
          selectIndex: 4,
          isRunning: false,
          isCrossCountry: false,
          isGym: false,
          isRope: false,
          isLevel: true,
          isActivity: false,
        });
        break;
      case "活动卡":
        this.setData({
          selectIndex: 5,
          isRunning: false,
          isCrossCountry: false,
          isGym: false,
          isRope: false,
          isLevel: false,
          isActivity: true,
        });
        break;
        case "瑜伽卡":
          this.setData({
            selectIndex: 6,
            isRunning: false,
            isCrossCountry: false,
            isGym: true,
            isRope: false,
            isLevel: false,
            isActivity: false,
          });
          break;
    }
  },

  // 上传图片
  afterRead: function (event) {
    const { file } = event.detail;
    let isAddImg = this.data.images.length != 0;

    this.setData({
      images: this.data.images.concat(file),
    });
    this.uploadToCloud(isAddImg, file);
  },
  uploadToCloud(isAddImg, file) {
    let images = file;
    if (!images.length) {
      wx.showToast({ title: "请选择图片", icon: "none" });
    } else {
      wx.showLoading({
        title: "图片上传中...",
      });
      this.setData({
        isUploadingImg: true,
      });
      const uploadTasks = images.map((file, index) =>
        this.uploadFilePromise(file)
      );
      Promise.all(uploadTasks)
        .then((data) => {
          console.log(data);
          wx.showToast({ title: "上传成功", icon: "none" });
          let filePath = data.map((item) => {
            return { url: item.fileID };
          });
          var filePaths = [];
          let lenght = this.data.images.length;
          let newLength = filePath.length;
          if (isAddImg) {
            this.data.images.splice(lenght - newLength, newLength);
            filePaths = this.data.images.concat(filePath);
          } else {
            filePaths = filePath;
          }
          console.log(filePaths);
          this.setData({ cloudPath: data, images: filePaths });
          wx.hideLoading();
          this.setData({
            isUploadingImg: false,
          });
        })
        .catch((e) => {
          wx.showToast({ title: "上传失败,请重新上传", icon: "none" });
          console.log(e);
          wx.hideLoading();
          this.setData({
            isUploadingImg: false,
          });
        });
    }
  },

  uploadFilePromise(chooseResult) {
    const cloudPath =
      `cloudbase/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}` +
      chooseResult.url.match(/\.[^.]+?$/);
    return wx.cloud.uploadFile({
      cloudPath: cloudPath,
      filePath: chooseResult.url,
    });
  },

  deleteImage: function (event) {
    console.log(event.detail.index);
    let { images, cloudPath } = this.data;
    images.splice(event.detail.index, 1);
    cloudPath.splice(event.detail.index, 1);
    this.setData({
      images: images,
      cloudPath: cloudPath,
    });
  },

  doUploadImage: function (filePath) {
    // 上传图片
    const cloudPath =
      `cloudbase/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}` +
      filePath.match(/\.[^.]+?$/);
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: (res) => {
        console.log(res);
        this.data.images.push(res.fileID);
        this.setData({ images: this.data.images });
      },
      fail: (e) => {
        console.error("[上传文件] 失败：", e);
        wx.showToast({
          icon: "none",
          title: "上传失败",
        });
      },
      complete: () => {
        wx.hideLoading();
      },
    });
  },
  onClickedRace: function (event) {
    this.setData({
      isRace: event.detail,
    });
  },
  onClickedActivity: function (event) {
    this.setData({
      isActivity: event.detail,
    });
  },

  onClickSubmit () {
    if (this.data.isAddCarding) {
      return;
    }
    this.sendDataToServer() // TODO 屏蔽订阅消息
    // this.setData({
    //   isAddCarding:true
    // })
    // wx.getSetting({
    //   withSubscriptions: true, //  这里设置为true,下面才会返回mainSwitch
    //   success: (res) => {
    //     console.log(res);
    //     // 调起授权界面弹窗
    //     if (res.subscriptionsSetting.mainSwitch) {
    //       // 用户打开了订阅消息总开关
    //       if (res.subscriptionsSetting.itemSettings != null) {
    //         // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
    //         let moIdState =
    //           res.subscriptionsSetting.itemSettings[
    //             "AqURRo0byhrs6tPkYniHWCHKWRowRDDcslP6WN_f4nc"
    //           ]; // 用户同意的消息模板id
    //         console.log(moIdState);
    //         if (moIdState === "accept") {
    //           console.log("接受了消息推送");
    //         } else if (moIdState === "reject") {
    //           console.log("拒绝消息推送");
    //         } else if (moIdState === "ban") {
    //           console.log("已被后台封禁");
    //         }
    //         that.sendDataToServer();
    //       } else {
    //         // 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
    //         wx.showModal({
    //           title: "提示",
    //           content: "请授权开通服务通知",
    //           showCancel: true,
    //           success: (ress) => {
    //             if (ress.confirm) {
    //               wx.requestSubscribeMessage({
    //                 // 调起消息订阅界面
    //                 tmplIds: ["AqURRo0byhrs6tPkYniHWCHKWRowRDDcslP6WN_f4nc"],
    //                 success(res) {
    //                   console.log("订阅消息 成功 ");
    //                   console.log(res);
    //                   that.sendDataToServer();

    //                   wx.setSubscribeMessageSetting({
    //                     itemSettings: {
    //                       key: '签到打卡',
    //                       value: [
    //                         "AqURRo0byhrs6tPkYniHWCHKWRowRDDcslP6WN_f4nc"
    //                       ]
    //                     } 
    //                   })

    //                 },
    //                 fail(er) {
    //                   that.sendDataToServer();
    //                   console.log("订阅消息 失败 ");
    //                   console.log(er);
    //                 },
    //               });
    //             }
    //           },
    //         });
    //       }
    //     } else {
    //       console.log("订阅消息未开启");
    //     }
    //   },
    //   fail: function (error) {
    //     that.setData({
    //       isAddCarding: false,
    //     });
    //     console.log(error);
    //   },
    // });
  },

  sendDataToServer: function () {
    if (this.data.isUploadingImg) {
      wx.showToast({
        title: "图片正在上传...",
      });
      return;
    }
    var r = /^\+?[1-9][0-9]*$/;
    switch (this.data.selectIndex) {
      case 0: // 跑步卡
        if (!this.data.distance) {
          wx.showModal({
            title: "提交错误",
            content: "请输入跑步距离",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        if (!this.isNumber(this.data.distance)) {
          wx.showModal({
            title: "提交错误",
            content: "跑步距离必须是大于零的实数",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        if (!this.data.speed) {
          wx.showModal({
            title: "提交错误",
            content: "请输入运动配速",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }

        break;
      case 2: // 越野卡
        if (!this.data.distance) {
          wx.showModal({
            title: "提交错误",
            content: "请输入跑步距离",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        if (!this.isNumber(this.data.distance)) {
          wx.showModal({
            title: "提交错误",
            content: "跑步距离必须是大于零的实数",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }

        if (!this.data.speed) {
          wx.showModal({
            title: "提交错误",
            content: "请输入运动配速",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        if (!this.data.altitude) {
          wx.showModal({
            title: "提交错误",
            content: "请输入爬升距离",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        if (!this.isNumber(this.data.altitude)) {
          wx.showModal({
            title: "提交错误",
            content: "爬升距离必须是大于零的实数",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        break;
      case 3: // 跳绳
        if (!this.data.ropeNo) {
          wx.showModal({
            title: "提交错误",
            content: "请输入跳绳个数",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        if (!r.test(this.data.ropeNo)) {
          wx.showModal({
            title: "提交错误",
            content: "跳绳个数正整数",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        break;
      case 4: // 爬楼梯
        if (!this.data.level) {
          wx.showModal({
            title: "提交错误",
            content: "请输入爬楼层数",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        if (!r.test(this.data.level)) {
          wx.showModal({
            title: "提交错误",
            content: "爬楼层数需要是正整数",
            confirmText: "我知道了",
            showCancel: false,
            success: function (res) {},
          });
          return;
        }
        break;
    }
    if (!this.data.time) {
      wx.showModal({
        title: "提交错误",
        content: "请输入运动时间",
        confirmText: "我知道了",
        showCancel: false,
        success: function (res) {},
      });
      return;
    }
    if (!r.test(this.data.time)) {
      wx.showModal({
        title: "提交错误",
        content: "运动时间需要是整数",
        confirmText: "我知道了",
        showCancel: false,
        success: function (res) {},
      });
      return;
    }

    if (this.data.heartrate && !r.test(this.data.heartrate)) {
      wx.showModal({
        title: "提交错误",
        content: "运动心率需要是正整数",
        confirmText: "我知道了",
        showCancel: false,
        success: function (res) {},
      });
      return;
    }

    if (this.data.calorie && !r.test(this.data.calorie)) {
      wx.showModal({
        title: "提交错误",
        content: "卡路里需要是正整数",
        confirmText: "我知道了",
        showCancel: false,
        success: function (res) {},
      });
      return;
    }

    if (this.data.images.length < 1) {
      wx.showModal({
        title: "提交错误",
        content: "至少需要上传一张打卡图",
        confirmText: "我知道了",
        showCancel: false,
        success: function (res) {},
      });
      return;
    }

    console.log(this.data.images[0]);
    if (
      this.data.images.length > 0 &&
      this.data.images[0].url.indexOf("cloud") == -1
    ) {
      wx.showModal({
        title: "提交错误",
        content: "图片还未上传成功哦，请重新上传图片...",
        confirmText: "我知道了",
        showCancel: false,
        success: function (res) {},
      });
      return;
    }

    wx.showLoading({
      title: "打卡中，请稍等...",
    });
    console.log(this.data);
    var userInfo = wx.getStorageSync("userInfo");
    var avatarUrl = wx.getStorageSync("avatarUrl")
    console.log('userInfo', userInfo, 'avatarUrl', avatarUrl)
    var nickName = wx.getStorageSync("nickName");
    wx.cloud.callFunction({
      name: "addCard",
      data: {
        type: app.globalData.types[this.data.selectIndex],
        distance: this.data.distance,
        time: this.data.time,
        speed: this.data.speed,
        message: this.data.message,
        level: this.data.level,
        ropeNo: this.data.ropeNo,
        heartrate: this.data.heartrate,
        images: this.data.images.map((item) => {
          return item.url;
        }),
        calorie: this.data.calorie,
        altitude: this.data.altitude,
        status: "unChecked",
        isRace: this.data.isRace,
        isActivity: this.data.isActivity,
        point: 0,
        userInfo: {
          avatarUrl: avatarUrl,
          nickName: nickName,
        },
      },
      success: (res) => {
        wx.hideLoading();
        if (res.result.success) {
          wx.showToast({
            icon: "none",
            title: "打卡成功",
            duration: 2000,
          });
          wx.navigateBack();
        } else {
          wx.showToast({
            icon: "none",
            title: res.result.message,
            duration: 2000,
          });
        }
        this.setData({
          isAddCarding: false,
        });
      },
      fail: (e) => {
        wx.hideLoading();
        console.error("[上传文件] 失败：", e);
        wx.showToast({
          icon: "none",
          title: "打卡失败，请重试...",
        });
        this.setData({
          isAddCarding: false,
        });
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ types: app.globalData.types });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  //判断是不是一个数字 或者 一个字符串里全是数字
  isNumber: function (value) {
    if (value === undefined || value === null || value === "") {
      return false;
    }
    if (typeof value === "string") {
      //正整数
      var reNumber = /^\d+$/;
      //负整数
      var reNeNumber = /^-\d+$/;
      //正实数
      var reRealNumber1 = /^[1-9]\d*[.]\d+$/; //非零开头
      var reRealNumber2 = /^0[.]\d+$/; //零开头
      //负实数
      var reNeRealNumber1 = /^-[1-9]\d*[.]\d+$/; //非零开头
      var reNeRealNumber2 = /^-0[.]\d+$/; //零开头

      if (
        reNumber.test(value) ||
        reNeNumber.test(value) ||
        reRealNumber1.test(value) ||
        reRealNumber2.test(value) ||
        reNeRealNumber1.test(value) ||
        reNeRealNumber2.test(value)
      ) {
        return true;
      } else {
        return false;
      }
    } else if (typeof value === "number") {
      return true;
    } else {
      return false;
    }
  },
});
